//
//  CalculatorView.swift
//  BRCalculator
//
//  Created by 王亮 on 2018/11/21.
//  Copyright © 2018 王亮. All rights reserved.
//

import Foundation
import UIKit

class CalculatorView: UIView {
    
    typealias CalculatorGenerator = (Double) -> Double
    
    //0，输入的字符串，1，输入的字符是否需要保留
    var _showString = ("", false)
    var showString: (String, Bool) {
        set {
            self._showString = newValue
            //更新输入框数据
            self.showLabel.text = _showString.0
        }
        get {
            return _showString
        }
    }
    
    var lastCalculate: CalculatorGenerator?
    
    var showLabel: UILabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        showLabel.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: 80);
        showLabel.backgroundColor = UIColor.black
        showLabel.textColor = UIColor.white
        showLabel.textAlignment = .right
        showLabel.font = UIFont.systemFont(ofSize: 30.0)
        showLabel.text = "0.0"
        self.addSubview(showLabel)
        
        var origin = CGPoint(x: 0, y: 80)
        let itemWidth = frame.size.width / 4
        let itemHeight = itemWidth
        for row in CalculatorView.elementTitles {
            for col in row {
                guard let element = CalculatorView.elements[col] as? UIButton else {
                    continue
                }
                element.frame = CGRect(origin: origin, size: CGSize(width: itemWidth, height: itemHeight))
                element.setTitle(col, for: .normal)
                element.setTitleColor(UIColor.black, for: .normal)
                element.backgroundColor = UIColor.orange
                element.setBackgroundImage(UIButton.getImageWithColor(color: UIColor.orange), for: .normal)
                element.setBackgroundImage(UIButton.getImageWithColor(color: UIColor.gray), for: .selected)
                element.addTarget(self, action: #selector(CalculatorView.clickActionButton(_:)), for: .touchUpInside)
                self.addSubview(element)
                
                origin.x = origin.x + itemWidth
            }
            origin.x = 0;
            origin.y += itemHeight
        }
    }
    
     @objc
     func clickActionButton(_ btn: UIButton) {
        if btn.isSelected { return }//间接运算符需要保持选中状态，如果一直是选中状态，重复点击不进行计算
        //重置按钮点击状态
        self.resetActionButtonSelectedStatus()
        guard let element = btn as? BaseElement else {
            return
        }
        if element.elementType == .numElement {
            //数字累加
            if !self.showString.1 {
                self.showString.0 = ""
            }
            self.showString.1 = true
            let numString = btn.title(for: .normal) ?? ""
            self.showString.0.append(numString)
        } else {
            //运算符
            //1.判断是否存在待计算的表达式
            //2.区分当前表达式是直接计算返回还是等待输入
            guard var num = Double(self.showString.0) else {
                self.lastCalculate = nil
                self.showString.0 = "0.0"
                self.showString.1 = false
                return
            }
            if (self.lastCalculate != nil) {
                if self.showString.1 == true {
                    self.showString.0 = "\(self.lastCalculate!(num))"
                    self.lastCalculate = nil;
                    num = Double(self.showString.0) ?? 0
                }
            }
            guard let calElement = element as? CalculationElement else {
                return
            }
            if calElement.calType == .inDirectCal {
                self.lastCalculate = calElement.calculate(a: num)
                self.showString.1 = false
                btn.isSelected = true
            } else if calElement.calType == .directCal {
                self.showString.0 = "\(calElement.directCalculate(a: num))"
                self.showString.1 = false
            }
        }
    }
    
    func resetActionButtonSelectedStatus() {
        for subView in self.subviews {
            guard let btn = subView as? UIButton else {
                continue
            }
            btn.isSelected = false
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CalculatorView {

    static var elementTitles: Array<Array<String>> {
        return [["AC","+/-","%","÷"],
                ["7","8","9","x"],
                ["4","5","6","-"],
                ["1","2","3","+"],
                ["0",".","="]]
    }
    
    static var elements: [String: BaseElement] {
        
        let supportedElements: [String: BaseElement] = [
            "1": NumberView(),
            "2": NumberView(),
            "3": NumberView(),
            "4": NumberView(),
            "5": NumberView(),
            "6": NumberView(),
            "7": NumberView(),
            "8": NumberView(),
            "9": NumberView(),
            "0": NumberView(),
            ".": NumberView(),
            EqualCalculateView.elementName: EqualCalculateView(),
            AddCalculateView.elementName: AddCalculateView(),
            SubCalculateView.elementName: SubCalculateView(),
            MultiplyCalculateView.elementName: MultiplyCalculateView(),
            DivideCalculateView.elementName: DivideCalculateView(),
            ACCalculateView.elementName: ACCalculateView(),
            NegateCalculateView.elementName: NegateCalculateView(),
            PercentCalculateView.elementName: PercentCalculateView(),
        ]
        return supportedElements
    }
    
}
